import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ClientConsole implements ClientIF {
	/**
	 * The default port to connect on.
	 */
	final public static int DEFAULT_PORT = 5555;
	
	/**
	 * The instance of the client that created this ClientLoader.
	 */
	ClientHandler client;
	
	public ClientConsole(String host, int port){
		try {
	      client = new ClientHandler(host, port, this);
	    } 
	    catch(IOException exception) {
	      System.out.println("Error: Can't setup connection!" + " Terminating client.");
	      System.exit(1);
	    }
	}
	
	 /**
	   * This method waits for input from the console.  Once it is 
	   * received, it sends it to the client's message handler.
	   */
	  public void accept() 
	  {
	    try
	    {
	      BufferedReader fromConsole = new BufferedReader(new InputStreamReader(System.in));
	      String message;

	      while (true) {
	        message = fromConsole.readLine();
	        if (message.equals("3")){
	        	System.out.println("Disconnected from Server");
	        	client.quit();
	        }
	        client.handleMessageFromClientUI(message);
	      }
	    } catch (Exception ex) {
	      System.out.println("Unexpected error while reading from console!");
	    }
	  }

	  /**
	   * This method overrides the method in the ChatIF interface.  It
	   * displays a message onto the screen.
	   *
	   * @param message The string to be displayed.
	   */
	  public void displayMsg(String message) {
	    System.out.println("> " + message);
	  }
	
	@Override
	public void displayMenu() {
		System.out.println("Client Menu:");
		System.out.println("1. Print query result from db");
		System.out.println("2. Add value to db");
		System.out.println("3. Disconnect and exit");
	}
	
	/**
	  * This method is responsible for the creation of the Client UI.
	  *
	  * @param args[0] The host to connect to.
	  */
	public static void main(String[] args){
	    String host = "";
	    int port = 0;  //The port number

	    try{
	      host = args[0];
	    }catch(ArrayIndexOutOfBoundsException e){
	      host = "localhost";
	    }
	    
	    try{
	    	port = Integer.parseInt(args[1]);
	    }catch(ArrayIndexOutOfBoundsException e){
		      port = DEFAULT_PORT;
	    }
	    ClientConsole cc = new ClientConsole(host, port);
	    cc.displayMenu();
	    cc.accept();  //Wait for console data
	}
}

